package xiaohui;

public class CycleLinkedTest {
    public static void main(String[] args) {
        Node node1 = new Node(5);
        Node node2 = new Node(3);
        Node node3 = new Node(7);
        Node node4 = new Node(2);
        Node node5 = new Node(6);
        Node node6 = new Node(8);
        Node node7 = new Node(1);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = node7;
        node7.next = node4;
        int cycleLength = 0;
        boolean existCycle = false;
        Node p1 = node1, p2 = node1;
        while (p2 != null && p2.next != null) {
            p1 = p1.next;
            p2 = p2.next.next;
            if (existCycle) {
                cycleLength++;
            }
            if (p1 == p2) {
                System.out.println("存在环形");
                if (existCycle) {
                    break;
                }
                existCycle = true;
            }
        }
        System.out.println("环的长度" + cycleLength);
    }

    private static class Node {
        int data;
        Node next;

        Node(int data) {
            this.data = data;
        }
    }
}
